//
//  RegisterViewController.m
//  homeland
//
//  Created by Alawn on 14-1-14.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "RegisterViewController.h"
#import "StreetInfoItem.h"
#import "StreetInfoItem.h"
#import "IQKeyboardManager.h"

#define USER_NAME_FIELD_TAG 1001
#define USER_PASSWORD_FIELD_TAG 1002
#define USER_REPASSWORD_FIELD_TAG 1003
#define USER_PHONE_FIELD_TAG 1004
#define USER_ADDRESS_FIELD_TAG 1005

@interface RegisterViewController ()
@property (assign, nonatomic) BOOL liveInFlag;
@property (assign, nonatomic) BOOL workInFlag;
@property (assign, nonatomic) NSInteger choosedStreetId;
@property (strong, nonatomic) CommitteesByStreetService *streetService;
@property (strong, nonatomic) NSArray *streetArray;
@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    self.title = @"用户注册";
    //    self.navigationItem.rightBarButtonItem = getCustomNavButton(@"忘记密码", self, @selector(rightBtAction:));
//    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, CGRectGetMaxY(self.loginBtn.frame)+10.0f);
    [self.scrollView addSubview:self.contentView];
    self.scrollView.contentSize = self.contentView.frame.size;
    //昵称
    self.userNameField.inputAccessoryView = [self getInputAccessoryView];
    self.userNameField.tag = USER_NAME_FIELD_TAG;
    self.userNameField.delegate = self;
    self.userNameField.returnKeyType = UIReturnKeyNext;
    //密码
    self.userPasswordField.inputAccessoryView = [self getInputAccessoryView];
    self.userPasswordField.tag = USER_PASSWORD_FIELD_TAG;
    self.userPasswordField.delegate = self;
    self.userPasswordField.returnKeyType = UIReturnKeyNext;
    //重新输入密码
    self.userRepasswordField.inputAccessoryView = [self getInputAccessoryView];
    self.userRepasswordField.tag = USER_REPASSWORD_FIELD_TAG;
    self.userRepasswordField.delegate = self;
    self.userRepasswordField.returnKeyType = UIReturnKeyNext;
    //手机号
    self.userPhoneField.inputAccessoryView = [self getInputAccessoryView];
    self.userPhoneField.tag = USER_PHONE_FIELD_TAG;
    self.userPhoneField.delegate = self;
    self.userPhoneField.returnKeyType = UIReturnKeyNext;
    //地址
    self.userAddressField.inputAccessoryView = [self getInputAccessoryView];
    self.userAddressField.tag = USER_ADDRESS_FIELD_TAG;
    self.userAddressField.delegate = self;
    self.userAddressField.returnKeyType = UIReturnKeyDone;
    //读取地址
    self.streetService = [CommitteesByStreetService new];
    self.streetService.delegate = self;
    [self.streetService loadDataWithKey:nil];
    self.choosedStreetId = -1;
    //    [self.autoLoginBtn setTitleColor:[UIColor darkTextColor] forState:UIControlStateHighlighted];
    //    [self.registerBtn setTitleColor:[UIColor darkTextColor] forState:UIControlStateHighlighted];
    //    //检查自动登录的标识
    //    NSString *autoLoginFlag = [DataStoreService loadFromKeychain:AUTO_LOGIN_FLAG];
    //    if (autoLoginFlag && [autoLoginFlag isEqualToString:AUTO_LOGIN_ENABLE]) {
    //        self.autoLoginCheckBoxImage.image = [UIImage imageNamed:@"checkbox.png"];
    //    } else {
    //        self.autoLoginCheckBoxImage.image = [UIImage imageNamed:@"uncheckbox.png"];
    //    }
    [UserInfoService getUserInfoService].delegate = self;
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [[IQKeyboardManager sharedManager] setEnable:YES];
}

#pragma mark - Button Methods
-(void)rightBtAction:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"忘记密码正在建设中..." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
//注册事件
- (IBAction)loginBtnAction:(id)sender
{
    NSString *userName = self.userNameField.text;
    NSString *userPass = self.userPasswordField.text;
    NSString *phone = self.userPhoneField.text;
    if (!userName || userName.length == 0) {
        [self showAlertWithMsg:@"用户名不能为空"];
        [self.userNameField becomeFirstResponder];
        return;
    }
    if (!userPass || userPass.length == 0) {
        [self showAlertWithMsg:@"密码不能为空"];
        [self.userPasswordField becomeFirstResponder];
        return;
    }
    if (!self.userRepasswordField.text || self.userRepasswordField.text.length == 0) {
        [self showAlertWithMsg:@"确认密码不能为空"];
        [self.userRepasswordField becomeFirstResponder];
        return;
    }
    if (!phone || phone.length == 0) {
        [self showAlertWithMsg:@"手机号不能为空"];
        [self.userPhoneField becomeFirstResponder];
        return;
    }
    if (self.choosedStreetId == -1) {
        [self showAlertWithMsg:@"请选择街道"];
        return;
    }
 
    //调用登录
//    [self startLoadingViewWithText:@"正在注册..."];
//        [[UserInfoService getUserInfoService] checkUserLoginWithName:userName andPassword:userPass];

    //请求注册  05-06
//    [[UserInfoService getUserInfoService] addUserWithName:userName Password:userPass Phone:phone Address:self.userAddressField.text StreetId:self.choosedStreetId LiveHere:self.liveInFlag WorkHere:self.workInFlag];
    
    //跳转到验证手机页
    RegisterCheckPhoneViewController *registerCheckPhoneVC = [[RegisterCheckPhoneViewController alloc]initWithNibName:@"RegisterCheckPhoneViewController" bundle:nil];
    registerCheckPhoneVC.userName = userName;
    registerCheckPhoneVC.password = userPass;
    registerCheckPhoneVC.phone = phone;
    registerCheckPhoneVC.address =self.userAddressField.text;
    registerCheckPhoneVC.choosedStreetId =self.choosedStreetId;
    registerCheckPhoneVC.liveHere = self.liveInFlag;
    registerCheckPhoneVC.workHere = self.workInFlag;
    [self.navigationController pushViewController:registerCheckPhoneVC animated:YES];
    
}

-(void)showAlertWithMsg:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (IBAction)autoLoginBtnAction:(id)sender
{
    NSString *autoLoginFlag = [DataStoreService loadFromKeychain:AUTO_LOGIN_FLAG];
    if (autoLoginFlag && [autoLoginFlag isEqualToString:AUTO_LOGIN_ENABLE]) {
        //之前选的是自动登录
        self.autoLoginCheckBoxImage.image = [UIImage imageNamed:@"uncheckbox.png"];
        [DataStoreService saveToKeychain:AUTO_LOGIN_FLAG data:AUTO_LOGIN_DISABLE];
    } else {
        //之前选的是不自动登录
        self.autoLoginCheckBoxImage.image = [UIImage imageNamed:@"checkbox.png"];
        [DataStoreService saveToKeychain:AUTO_LOGIN_FLAG data:AUTO_LOGIN_ENABLE];
    }
}

- (IBAction)streetButtonAction:(id)sender
{
    NSLog(@"准备选择地址");
    ChooseStreetViewController *streetVC = [[ChooseStreetViewController alloc] initWithNibName:@"ChooseStreetViewController" bundle:nil];
    streetVC.usedForPersonalInfo = YES;
    streetVC.delegate = self;
    streetVC.streetListService = self.streetService;
    [self.navigationController pushViewController:streetVC animated:YES];
}

- (IBAction)liveButtonAction:(id)sender
{
    if (self.liveInFlag) {
        //取消选中
        self.liveButtonCheckbox.image = [UIImage imageNamed:@"uncheckbox.png"];
        self.liveInFlag = NO;
    } else {
        //选中
        self.liveButtonCheckbox.image = [UIImage imageNamed:@"checkbox.png"];
        self.liveInFlag = YES;
    }
}

- (IBAction)workButtonAction:(id)sender
{
    if (self.workInFlag) {
        //取消选中
        self.workButtonCheckbox.image = [UIImage imageNamed:@"uncheckbox.png"];
        self.workInFlag = NO;
    } else {
        //选中
        self.workButtonCheckbox.image = [UIImage imageNamed:@"checkbox.png"];
        self.workInFlag = YES;
    }
}

- (IBAction)registerBtnAction:(id)sender {
    
}

#pragma mark - Text Field Methods

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    switch (textField.tag) {
        case USER_NAME_FIELD_TAG:
            [self.userPasswordField becomeFirstResponder];
            break;
        case USER_PASSWORD_FIELD_TAG:
            [self.userRepasswordField becomeFirstResponder];
            break;
        case USER_REPASSWORD_FIELD_TAG:
            [self.userPhoneField becomeFirstResponder];
            break;
        case USER_PHONE_FIELD_TAG:
            [self.userAddressField becomeFirstResponder];
            break;
        case USER_ADDRESS_FIELD_TAG:
            [self.userAddressField resignFirstResponder];
            break;
        default:
            break;
    }

    return YES;
}

//注册完成回调函数
#pragma mark - User Info Service Methods
-(void)loadUserInfoFinished:(id)result
{
    //关闭加载框
    [self stopLoadingView];
    
    isStart=1;//成功登录
//    [[UserInfoService getUserInfoService] loginSuccessHandler:result];
    //自动登录 start 04-07
//    [[UserInfoService getUserInfoService] autoLogin];
//    [self.navigationController popToRootViewControllerAnimated:YES];
    //自动登录 end 04-07
    //    NSString *autoLoginFlag = [DataStoreService loadFromKeychain:AUTO_LOGIN_FLAG];
    //    if (autoLoginFlag && [autoLoginFlag isEqualToString:AUTO_LOGIN_ENABLE]) {
    //        //勾选了自动登录，则在这里保存密码
    //        [DataStoreService saveToKeychain:AUTO_LOGIN_USER_NAME data:self.userNameField.text];
    //        [DataStoreService saveToKeychain:AUTO_LOGIN_USER_PASSWORD data:self.userPasswordField.text];
    //    } else {
    //        //没勾选自动登录，尝试清除数据
    //        [DataStoreService deleteFromKeychain:AUTO_LOGIN_USER_NAME];
    //        [DataStoreService deleteFromKeychain:AUTO_LOGIN_USER_PASSWORD];
    //    }
}

-(void)loadUserInfoFaild:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [self stopLoadingView];
}

#pragma mark - Street Choose delegate
-(void)choosedStreet:(NSInteger)streetId
{
    NSLog(@"选择了街道%d", streetId);
    self.choosedStreetId = streetId;
    [self.streetButton setTitle:[self getStreetNameById:streetId] forState:UIControlStateNormal];
}

-(NSString *)getStreetNameById:(NSInteger)streetId
{
    NSString *name = @"请选择";
    for (StreetInfoItem *item in self.streetArray) {
        if (item.item_id.integerValue == streetId) {
            name = item.item_name;
            break;
        }
    }
    return name;
}

#pragma mark - Data Service Method
-(void)loadDataFinished
{
    [self stopLoadingView];
    self.streetButton.enabled = YES;
    self.streetArray = self.streetService.dataList;
    [self.streetButton setTitle:[self getStreetNameById:self.choosedStreetId] forState:UIControlStateNormal];
}

-(void)loadDataFaild:(NSString *)msg
{
    [self stopLoadingView];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"读取街道列表失败,无法修改街道信息,请稍后重试." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    self.streetButton.enabled = NO;
}
@end
